给定一个二叉树的根节点 root ,返回 它的 中序 遍历 。

示例 1:

输出:[1,3,2]
输入:root = [1,null,2,3]
1
2

示例 2:

输入:root = []
输出:[]
1
2

示例 3:

输入:root = [1]
输出:[1]
1
2

代码实现

var inorderTraversal = function(root) {
    /**递归实现 */
    // const res = [];
    // const inorder = (root) => {
    //     // 终止条件
    //     if(!root) { return; }
    //     inorder(root.left);
    //     res.push(root.val);
    //     inorder(root.right);
    // }
    // inorder(root);
    // return res;
    /** 递归简化 */
    if(!root) return res;
    inorderTraversal(root.left, res);
    res.push(root.val);
    inorderTraversal(root.right, res);
    return res;
    /** 速度很快 */
    // const res = [], stk = [];
    // while(root || stk.length){
    //     while(root){
    //         stk.push(root);
    //         root = root.left;
    //     }
    //     root = stk.pop();
    //     res.push(root.val);
    //     root = root.right;
    // }
    // return res;
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
最后更新时间: 6/20/2022, 10:48:50 PM